import { ref, type Ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRoute } from 'vue-router'
import { defineStore } from 'pinia'
import api from '@/utils/api'
// 聊天消息类型定义
export interface ChatMessage {
  senderId: number
  receiverId: number
  content: string
  sendTime: string
  messageType: number  // 消息类型: 0-text 1-image 2-file
  isRead: number  // 是否已读: 0-未读 1-已读
}
// 联系人类型定义
export interface Contact {
  id: number
  username: string
  avatar: string
  unread_count: number
}

// 聊天状态管理Store
export const useChatStore = defineStore('chat', {
  state: () => ({
    totalUnreadCount: 0,
    isChatPageActive: false, // 标记是否在聊天页面
    unreadCheckInterval: null as number | null, // 轮询定时器ID
    lastUnreadCheck: 0, // 最后检查时间
  }),
  
  actions: {
    // 轮询获取未读数（仅在非聊天页面时）
    startUnreadPolling() {
      if (this.isLogin) {
        if (this.unreadCheckInterval) {
          clearInterval(this.unreadCheckInterval)
        }
      }
      // 每30秒轮询一次未读消息
      this.unreadCheckInterval = window.setInterval(async () => {
        if (!this.isChatPageActive) { // 只在非聊天页面轮询
          await this.fetchUnreadCount()
        }
      }, 30000) // 30秒
    },
    
    // 停止轮询
    stopUnreadPolling() {
      if (this.unreadCheckInterval) {
        clearInterval(this.unreadCheckInterval)
        this.unreadCheckInterval = null
      }
    },
    
    // 获取未读数
    async fetchUnreadCount() {
      if (!this.isLogin) {
        return
      }
      try {
        const response = await api.get('/chat/unread_count/')
        this.totalUnreadCount = response.data.unreead_count || 0
        this.lastUnreadCheck = Date.now()
      } catch (error) {
        console.error('获取未读数失败:', error)
        // 可以选择不更新或显示错误状态
      }
    },
    
    // 设置聊天页面活跃状态
    setChatPageActive(active: boolean) {
      this.isChatPageActive = active
      
      if (active) {
        // 进入聊天页面时停止轮询
        this.stopUnreadPolling()
      } else {
        // 离开聊天页面时开始轮询
        this.startUnreadPolling()
        // 立即获取一次未读数
        this.fetchUnreadCount()
      }
    },
    
    // 在应用初始化时设置轮询
    initializeUnreadTracking() {
      // 如果不在聊天页面，开始轮询
      if (!this.isChatPageActive) {
        this.startUnreadPolling()
        this.fetchUnreadCount()
      }
    },
    
    // 清理资源
    cleanup() {
      this.stopUnreadPolling()
    }
  },
  getters: {
    isLogin: (state) => {
      // 从 user store 或其他地方获取登录状态
      const userStore = useUserStore()
      return userStore.isLogin
    }
  }
})
// WebSocket连接状态
export type WebSocketStatus = 'connecting' | 'authenticating' | 'connected' | 'disconnected' | 'error' 

// 聊天WebSocket类
export class ChatWebSocket {
  private ws: WebSocket | null = null
  private url: string
  private reconnectAttempts: number = 0
  private maxReconnectAttempts: number = 5
  private reconnectDelay: number = 3000
  private access: string

  public messages: Ref<ChatMessage[]> = ref([])
  public contacts: Ref<Contact[]> = ref([]) // 新增联系人列表
  public status: Ref<WebSocketStatus> = ref('disconnected')
  public error: Ref<string | null> = ref(null)
  public activeContact: Ref<{ id: number;username: string} | null> = ref(null) // 当前选中的联系人

  constructor(url: string, access: string) {
    this.url = url
    this.access = access
  }

  // 连接到WebSocket服务器
  connect() {
    const route = useRoute()
    try {
      this.status = 'connecting'
      this.ws = new WebSocket(this.url)

      this.ws.onopen = () => {
        console.log('WebSocket连接已建立，开始认证...')
        this.status = 'authenticating'
        this.authenticate()
      }

      this.ws.onmessage = (event) => {
        this.handleMessage(event.data)
      }

      this.ws.onclose = () => {
        // 仅在聊天页面尝试重连
        const currentPath = window.location.pathname
        if (!currentPath.includes('/chat')) return
        console.log('WebSocket连接已关闭')
        this.status = 'disconnected'
        this.attemptReconnect()
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.status = 'error'
        this.error = '连接错误'
      }
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.status = 'error'
      this.error = '连接失败'
    }
  }

  // 认证
  private authenticate() {
    console.log('进入验证')
    if (this.ws && this.status === 'authenticating') {
      const authMessage = {
        type: 'authenticate',
        access: this.access
      }
      this.ws.send(JSON.stringify(authMessage))
      console.log('发送认证消息:', authMessage)
    }
  }

  // 处理接收到的消息
  private handleMessage(data: string) {
    try {
      const messageData = JSON.parse(data)
      console.log('收到消息:', messageData)

      // 认证成功后，服务器会发送联系人列表
      if (this.status === 'authenticating' && messageData.type === 'contacts') {
        this.contacts = messageData.contacts
        this.status = 'connected'
        console.log('认证成功，收到联系人列表:', this.contacts)
        return // 认证成功后直接返回，不再处理其他逻辑
      }

      // 如果认证失败
      if (this.status === 'authenticating' && messageData.type === 'error') {
        console.error('认证失败:', messageData.message)
        this.status = 'error'
        this.error = messageData.message || '认证失败'
        this.ws?.close() // 认证失败主动关闭
        return
      }

      // 认证成功后处理其他消息
      if (this.status !== 'connected') {
        return // 如果未连接成功，忽略其他消息
      }

      switch (messageData.type) {
        case 'contacts':
          // 更新联系人列表
          this.contacts = messageData.contacts
          console.log('更新联系人列表:', this.contacts)
          break

        case 'history_messages':
          // 清空当前消息并加载历史消息
          this.messages = messageData.history_messages.map((msg: any) => ({
            senderId: msg.Sender_id,
            receiverId: msg.Receiver_id,
            content: msg.content,
            sendTime: msg.send_time, 
            messageType: msg.msg_type,
            isRead: msg.if_read
          }))

          break

        case 'message':
          // 接收实时消息
          const newMessage: ChatMessage = {
            senderId: messageData.message.Sender_id, 
            receiverId: messageData.message.Receiver_id, 
            content: messageData.message.content,
            sendTime: messageData.message.send_time,
            messageType: messageData.message.msg_type,
            isRead: messageData.message.if_read
          }
          this.messages.push(newMessage)
          break

        case 'error':
          console.error('服务器错误:', messageData.message)
          this.error = messageData.message
          break

        default:
          console.warn('未知消息类型:', messageData.type, messageData)
      }
    } catch (error) {
      console.error('处理消息失败:', error, data)
    }
  }

  sendMessage(content: string, receiverId: number, messageType: number = 0) {
    if (this.ws && this.status === 'connected') {
      const message = {
        type: 'message',
        message: {
          Sender_id: useUserStore().userInfo.id, // 假设用户ID字段为 id
          Receiver_id: receiverId,
          content: content,
          msg_type: messageType
          // send_time 由后端生成
        }
      }
      this.ws.send(JSON.stringify(message))
      return true
    }
    return false
  }

  // 加载历史消息 - 根据 receiverId
  loadHistory(receiverId: number) {
    
    if (this.ws) {
      const message = {
        type: 'message',
        message: {
          Sender_id: useUserStore().userInfo.id, // 假设用户ID字段为 id
          Receiver_id: receiverId,
          content: ' ', // 空格表示请求历史消息
          msg_type: 0
        }
      }
      this.ws.send(JSON.stringify(message))
    }
  }

  // 尝试重新连接
  private attemptReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)

      setTimeout(() => {
        this.connect()
      }, this.reconnectDelay)
    } else {
      console.log('达到最大重连次数，停止重连')
      this.error = '连接断开，请刷新页面重试'
    }
  }

  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }
}

// 创建聊天WebSocket实例的工厂函数
export const createChatWebSocket = () => {
  const userStore = useUserStore();
  // 获取用户token
  const access = userStore.userInfo.access
  if (!access) {
    throw new Error('用户未登录或令牌无效')
  }

  // 获取用户ID
  const myUid = userStore.userInfo.id
  if (!myUid) {
      throw new Error('无法获取当前用户ID')
  }

  // 构造WebSocket URL (假设后端WebSocket端点为/ws/chat/)
  const wsUrl = `ws://localhost:8000/api/ws/chat/`
  return new ChatWebSocket(wsUrl, access)
}